﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace EffiProz.Core.Lib
{
    public class EfzTaskQueue
    {
        /** The thread used to process commands */
        protected Thread taskRunnerThread;

        /** Special queue element to signal termination */
        protected static ThreadStart SHUTDOWNTASK = new ThreadStart(delegate() { });

        /**
         * true if thread should shut down after processing current task.
         *
         * Once set true, stays true forever
         */
        protected volatile bool _isShutdown;

        public Thread getTaskRunnerThread()
        {
            lock (this)
            {
                return taskRunnerThread;
            }
        }

        protected void clearThread()
        {
            lock (this)
            {
                taskRunnerThread = null;
            }
        }

        protected EfzDeque queue = new EfzDeque();



        public void run()
        {

            ThreadStart task;

            try
            {
                while (!_isShutdown)
                {
                    lock (queue)
                    {
                        task = (ThreadStart)queue.getFirst();
                    }

                    if (task == SHUTDOWNTASK)
                    {
                        _isShutdown = true;

                        lock (queue)
                        {
                            queue.clear();
                        }

                        break;
                    }
                    else if (task != null)
                    {
                        task.Invoke();

                        task = null;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            finally
            {
                clearThread();
            }
        }


        protected ThreadStart taskRunner;

        public EfzTaskQueue()
        {
            taskRunner = new ThreadStart(run);
        }

        public bool isShutdown()
        {
            return _isShutdown;
        }

        public void restart()
        {
            lock (this)
            {
                if (taskRunnerThread == null && !_isShutdown)
                {
                    taskRunnerThread = new Thread(taskRunner);

                    taskRunnerThread.Start();
                }
            }
        }

        public void execute(ThreadStart command)
        {

            if (!_isShutdown)
            {
                lock (queue)
                {
                    queue.addLast(command);
                }

                restart();
            }
        }

        public void shutdownAfterQueued()
        {
            lock (this)
            {
                if (!_isShutdown)
                {
                    lock (queue)
                    {
                        queue.addLast(SHUTDOWNTASK);
                    }
                }
            }
        }

        public void shutdownAfterCurrent()
        {
            lock (this)
            {
                _isShutdown = true;

                lock (queue)
                {
                    queue.clear();
                    queue.addLast(SHUTDOWNTASK);
                }
            }
        }

        public void shutdownImmediately()
        {
            lock (this)
            {
                _isShutdown = true;

                if (taskRunnerThread != null)
                {
                    taskRunnerThread.Interrupt();
                }

                lock (queue)
                {
                    queue.clear();
                    queue.addLast(SHUTDOWNTASK);
                }
            }
        }
    }
}
